package com.santu.edu.supporter.interceptor;

import cn.hutool.core.util.StrUtil;
import com.santu.edu.supporter.exception.BizException;
import com.santu.edu.supporter.exception.CustomError;
import com.santu.edu.supporter.util.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author luoyaoqi
 * @createTime 2024/2/23
 * @description
 */
@Slf4j
public class UserLoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头，header值为Authorization，承载token
        String token = request.getHeader(JWTUtils.header);
        if ("666666".equals(token)) {
            UserThreadLocal.set(token);
            return true;
        }
        //token不存在
        if (StrUtil.isBlank(token)) {
            String uri = request.getRequestURI();
            if (uri.contains("/user/get/user/by/userId")) {
                throw BizException.causeBy(CustomError.NOT_LOGIN_HOME);
            }
            log.error("输入的token为空,请求的地址为:{}",uri);
            throw BizException.causeBy(CustomError.NOT_LOGIN,"登录查看详情!");
        }
        //验证token
        String userId = JWTUtils.validateToken(token);
        if (StrUtil.isBlank(userId)) {
            throw BizException.causeBy(CustomError.NOT_LOGIN,"Token验证失败!");
        }
        UserThreadLocal.set(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求处理完成后，清除 ThreadLocal 中的数据，避免内存泄漏
        UserThreadLocal.remove();
    }
}
